#
#    Pixel War (Cliente) - Cliente de Juego Multiplayer Online
#    Copyright (C) 2010 - Francisco Rivera
#
#    This program is free software: you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation, either version 3 of the License, or
#    (at your option) any later version.
#
#    This program is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.
#
#    You should have received a copy of the GNU General Public License
#    along with this program.  If not, see <http://www.gnu.org/licenses/>.
#

import math
import pygame
from protocolo import Protocolo
from constantes import P_X, P_Y
from tools import JThread

def esta_entre(n, nm, nM):
    return (n >= nm) and (n < nM)
    
def angulo_to_dir(ang):
    if esta_entre(ang, 22.5*0, 22.5*1):
        return 's'
    elif esta_entre(ang, 22.5*1, 22.5*3):
        return 'se'
    elif esta_entre(ang, 22.5*3, 22.5*5):
        return 'e'
    elif esta_entre(ang, 22.5*5, 22.5*7):
        return 'ne'
    elif esta_entre(ang, 22.5*7, 22.5*9):
        return 'n'
    elif esta_entre(ang, 22.5*9, 22.5*11):
        return 'no'
    elif esta_entre(ang, 22.5*11, 22.5*13):
        return 'o'
    elif esta_entre(ang, 22.5*13, 22.5*15):
        return 'so'
    elif esta_entre(ang, 22.5*15, 22.5*16):
        return 's'
    else:
        print "error"

C_X = P_X/2
C_Y = P_Y/2

class Mouse:

    def __init__(self):    
        self.mouse = pygame.mouse
    
    def getAngulo(self):
        ''' Devuelve el angulo que se forma entre la posicion del mouse y el centro de la pantalla. '''
        angulo = self.getRawAngulo()
        return int(angulo)
        
    def getRawAngulo(self):    
        mx, my = self.mouse.get_pos()        
        angulo = math.degrees(math.atan2((mx - C_X),(my - C_Y)))
        if angulo < 0:
            angulo += 360
        return angulo


class MouseHandler(JThread):

    def __init__(self):
        JThread.__init__(self)
        self.enabled = False
        self.prot = Protocolo()
        self.mouse = Mouse()
        self.start()

    def activar(self):
        self.enabled = True

    def run(self):
        while JThread.JUGANDO:
            if self.enabled:
                clicks = pygame.mouse.get_pressed()
                if clicks[0]:
                    dir = angulo_to_dir(self.mouse.getAngulo())
                    self.prot.disparar(dir)
            pygame.time.wait(50)